<?php
use OSS\OssClient;

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();
checkFunc(70);

$now = time();
$success = $_GET['success'] ?? null;
$error = $_GET['error'] ?? null;
$action = $_GET['action'] ?? null;

$all_items = $DB->select('red_packet', '*');
$coupon_arr = $DB->select('red_packet_coupon',['id','coupon_name','batch_number']);
$dressup_arr = $DB->select('red_packet_dressup',['id','name']);

if($action) {
    if ($action == 'del') {
        checkFunc(71, '权限不足，无法操作');
        $aid = $_GET['id'] ?? null;
        if (!$aid) {
            $error = '无效的类型ID';
        } else {
            $DB->delete('red_packet', ['id' => $aid]);
            $success = '删除成功';
            operate_log('red_packet', 'delete', ['ID' => $aid]);
        }
    }
    else if($action == 'add_type') {
        checkFunc(71, '权限不足，无法操作');
        $method = $_POST['method'] ?? null;
        if(!in_array($method, ['new', 'edit'])) {
            $error = '无效的数据类型';
        } else {
            $edit_id = $_POST['edit_id'] ?? null;
            $cycle = $_POST['cycle'] ?? 0;
            $feed_times = $_POST['feed_times'] ?? 0;
            $siliao = $_POST['siliao'] ?? 0;
            $s_probability = $_POST['s_probability'] ?? 0;
            $yhq = $_POST['yhq'] ?? [];
            $pyhq = $_POST['pyhq'] ?? [];
            $pdressup = $_POST['pdressup'] ?? [];
            $derssup = $_POST['derssup'] ?? [];
            $no_reward = $_POST['no_reward'] ?? 0;

            $reward = [];
            if($siliao) {
                $reward[] = ['type' => 2, 'nums' => $siliao, 'probability' => $s_probability];
            }
            if($yhq) {
                $new = [];
                foreach($yhq as $val) {
                    foreach($coupon_arr as $key => $info) {
                        if($info['id'] == $val) {
                            $new[$key] = $val;
                        }
                    }
                }
                $yhq = $new;
                foreach($yhq as $key => $val) {
                    if(empty($pyhq[$key])) {
                        $pyhq[$key] = 0;
                    }
                    $reward[] = ['type' => 3, 'id' => $val, 'probability' => $pyhq[$key]];
                }
            }
            if($derssup) {
                $new = [];
                foreach($derssup as $val) {
                    foreach($dressup_arr as $key => $info) {
                        if($info['id'] == $val) {
                            $new[$key] = $val;
                        }
                    }
                }
                $derssup = $new;

                foreach ($derssup as $key => $val) {
                    if(empty($pdressup[$key])) {
                        $pdressup[$key] = 0;
                    }
                    $reward[] = ['type' => 1, 'id' => $val, 'probability' => $pdressup[$key]];
                }
            }
            if($no_reward) {
                $reward[] = ['type' => 4, 'probability' => $no_reward];

            }
            $data = [
                'cycle' => $cycle,
                'times' => $feed_times,
                'rewards' => json_encode($reward)
            ];
            if($method == 'edit' && $edit_id) {
                $DB->update('red_packet', $data, ['id'=>$edit_id]);
                operate_log('red_packet', 'edit', [
                    'ID' => $edit_id
                ]);
                $success = '修改成功';
            } else {
                $DB->insert('red_packet', $data);
                $id = $DB->id();
                if (!$id) $error = '创建失败';
                else {
                    $success = '添加成功';
                    operate_log('red_packet', 'new', [
                        'ID' => $id
                    ]);
                }
            }
        }
    }
    else {
        $error = '无效的操作';
    }
    goExit('red_packet_list.php?success=' . $success . '&error=' . $error);
}
if($coupon_arr) {
    $new_array = [];
    foreach($coupon_arr as $info) {
        $new_array[$info['id']] = $info;
    }
    $coupon_arr = $new_array;
}
if($dressup_arr) {
    $new_array = [];
    foreach($dressup_arr as $info) {
        $new_array[$info['id']] = $info;
    }
    $dressup_arr = $new_array;
}

display_header();

?>

<link href="css/jquery.dm-uploader.min.css" rel="stylesheet">
<style>
    #fileinp{
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
    }
</style>

<section class="content">
    <?php if($error) : ?>
        <div class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <span><?php echo $error; ?></span>
        </div>
    <?php endif ?>
    <?php if($success) : ?>
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon fa fa-check"></i> 成功</h4>
            <?php echo $success; ?>
        </div>
    <?php endif ?>

    <div class="box box-primary">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-search"></i> 红包奖励管理</h3>
            <span style="font-size:12px;color:#A9A9A9;">   注: 0轮为默认轮, 1轮为新手轮</span>
        </div>

        <div class="box-body" id="vbody">

            <button type="button" class="btn btn-primary pull-left add_type" style="margin-bottom:10px;">添加红包奖励</button>
            <table id="logtable" class="table table-bordered table-striped dataTable table-hover " role="grid" aria-describedby="example1_info">
                <thead>
                <tr>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">生效轮数</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">喂食次数</th>
                    <th class="" rowspan="1" colspan="1" width="250">奖励</th>
                    <th class="" rowspan="1" colspan="1" style="text-align:center">操作</th>
                </tr>
                </thead>
                <tbody>
                <?php if(!empty($all_items)) { foreach($all_items as $item) { ?>
                    <tr role="row" style="text-align:center;">
                        <td class="cycle"><?php echo $item['cycle']; ?></td>
                        <td class="times"><?php echo $item['times']; ?></td>
                        <td class="font12 left">
                            <span style="display:none" class="treward"><?php echo $item['rewards']; ?></span>
                            <?php
                            $rewards = json_decode($item['rewards'], true);
                            echo '<ul style="margin:0;padding:0;margin-left:20px;">';
                            foreach($rewards as $tw) {
                                switch ($tw['type']) {
                                    case 1:
                                        echo '<li>装扮 | ' . $dressup_arr[$tw['id']]['name'] . ' | 权重 : ' . $tw['probability'] . '</li>';
                                        break;
                                    case 2:
                                        echo '<li>饲料 | 数量 : ' . $tw['nums'] . ' | 权重 : ' . $tw['probability'] . '</li>';
                                        break;
                                    case 3:
                                        // var_dump($tw);exit;
                                        // echo '<li>批次号<ul style="margin:0;padding:0;margin-left:40px;">';
                                        // $coupon_arr[$tw['id']]['name'];
                                        // $ex_arr = explode(',', $tw['extra']);
                                        // foreach($ex_arr as $ex) {
                                        //     echo '<li>' . $ex . '</li>';
                                        // }
                                        // echo '</ul></li>';
                                        echo '<li>优惠券 | ' . $coupon_arr[$tw['id']]['coupon_name'] . ' | 权重 : ' . $tw['probability'] . '</li>';
                                        break;
                                    case 4:
                                        echo '<li> 无奖励 | 权重 : ' . $tw['probability'] . '</li>';
                                        break;
                                }
                            }
                            echo '</ul>';
                            ?>
                        </td>
                        <td >
                            <button type="button" class="btn btn-sm btn-success edit_type">修改</button> |
                            <button type="button" class="btn btn-sm btn-danger del_notice" iid="<?php echo $item['id']; ?>">删除</button>
                        </td>
                    </tr>
                <?php } } ?>
                </tbody>
            </table>

            <!-- 添加兑换类型 -->
            <div class="modal fade" id="modal-add-admin">
                <div class="modal-dialog modal-lg">
                    <form id="item_form" name="item_form" action="red_packet_list.php?action=add_type" method="post">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title"></h4>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" id="new_method" name="method" value="new" />
                                <input type="hidden" id="edit_id" name="edit_id" value="" />
                                <table border="0" width="100%" class="modal_table_style">
                                    <tr height="45">
                                        <th style="width: 120px">轮数:</th>
                                        <td><input type="text" class="form-control" size="20" name="cycle" id="cycle" /></td>
                                    </tr>
                                    <tr height="45">
                                        <th style="width: 120px">喂食次数:</th>
                                        <td><input type="text" class="form-control" size="20" name="feed_times" id="feed_times" /></td>
                                    </tr>
                                    <tr height="45">
                                        <th style="width: 120px">奖励饲料:
                                            <br><span style="color:#999;font-weight:normal;font-size:12px;">无饲料奖励请留空</span>
                                        </th>
                                        <td>
                                            <input type="number" class="form-control" style="display:inline;width:300px;" size="20" name="siliao" id="siliao" />
                                            权重 :
                                            <input type="number" class="form-control" style="display:inline;width:300px;" size="20" name="s_probability" id="s_probability" />
                                        </td>
                                    </tr>
                                    <tr height="45">
                                        <th style="width: 120px">可使用优惠券:</th>
                                        <td style="font-size:12px;">
                                            <div class="funcs_box" style="overflow-y:scroll;height:100px;padding:5px 10px; margin:10px 0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;border-left:1px solid #ccc;">
                                                <?php
                                                echo '<div class="pull-left">';
                                                foreach ($coupon_arr as $val){
                                                    echo '<label style="margin-right:15px;display:inline-block;">';
                                                    echo '<input type="checkbox" name="yhq[]" id="'.$val['id'].'" value="'.$val['id'].'"> ';
                                                    echo $val['coupon_name'];
                                                    echo '</label>';
                                                    echo '  权重 : <input type="number" class="form-control" style="display:inline;width:80px;" size="20" name="pyhq[]" id="pyhq_'.$val['id'].'" />';
                                                    echo '<br />';
                                                }
                                                echo '</div>';
                                                echo '<div style="clear:both"></div>';
                                                echo '</div>';
                                                ?>
                                            </div>
                                        </td>
                                    </tr>

                                    <tr height="45">
                                        <th style="width: 120px">可使用装扮:</th>
                                        <td style="font-size:12px;">
                                            <div class="funcs_box" style="overflow-y:scroll;height:auto;padding:5px 10px; margin:10px 0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;border-left:1px solid #ccc;">
                                                <?php
                                                echo '<div class="pull-left">';
                                                foreach ($dressup_arr as $val){
                                                    echo '<label style="margin-right:15px;display:inline-block;">';
                                                    echo '<input type="checkbox" name="derssup[]" id="'.$val['id'].'" value="'.$val['id'].'"> ';
                                                    echo $val['name'];
                                                    echo '</label>';
                                                    echo '  权重 : <input type="number" class="form-control" style="display:inline;width:80px;" size="20" name="pdressup[]" id="pdressup_'.$val['id'].'" />';
                                                    echo '<br />';
                                                }
                                                echo '</div>';
                                                echo '<div style="clear:both"></div>';
                                                echo '</div>';
                                                ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr height="45">
                                        <th style="width: 120px">不中奖权重:</th>
                                        <td><input type="number" class="form-control" size="20" name="no_reward" id="no_reward" /></td>
                                    </tr>

                                </table>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary submit_form">确定</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>

<script src="js/jquery.dm-uploader.min.js"></script>

<script type="text/javascript">

    $(function() {
        $('.add_type').click(function() {
            $('.modal-title').text('添加奖励');
            $('#cycle').val('');
            $('#feed_times').val('');
            $('#siliao').val('');
            $('#s_probability').val('');
            $('#no_reward').val('');

            var yhq = document.getElementsByName("yhq[]");
            var pyhq = document.getElementsByName("pyhq[]");
            for(var i=0;i<yhq.length;++i){
                $('#'+ yhq[i].id).prop("checked",false);
                $('#'+ pyhq[i].id).val('');
            }

            var derssup = document.getElementsByName("derssup[]");
            var pdressup = document.getElementsByName("pdressup[]");
            for(var i=0;i<derssup.length;++i){
                $('#'+ derssup[i].id).prop("checked",false);
                $('#'+ pdressup[i].id).val('');
            }
            $('#modal-add-admin').modal({
                backdrop: 'static',
            });
        });

        $('.edit_type').click(function() {
            $('.modal-title').text('修改奖励');
            $('#new_method').val('edit');
            var id = $(this).next().attr('iid');
            var cycle = $(this).parent().parent().find('.cycle').text();
            var times = $(this).parent().parent().find('.times').text();
            var treward = $(this).parent().parent().find('.treward').text();
            $('#edit_id').val(id);
            $('#cycle').val(cycle);
            $('#feed_times').val(times);

            var derssup = document.getElementsByName("derssup[]");
            var pdressup = document.getElementsByName("pdressup[]");
            var yhq = document.getElementsByName("yhq[]");
            var pyhq = document.getElementsByName("pyhq[]");
            var rewards = JSON.parse(treward);
            for(i in rewards) {
                switch(rewards[i]['type']) {
                    case 1:
                        $('input[type=checkbox]').each(function () {
                            let val = $(this).val();
                            var name = $(this).attr("name");
                            // console.log($(this).attr("name"));
                            // return;
                            if(val == rewards[i].id && name == 'derssup[]') {
                                $('input:checkbox[value='+val+']').prop('checked',true);
                                $('#pdressup_'+ rewards[i].id).val(rewards[i]['probability']);
                            }
                        });
                        break;
                    case 2:
                        $('#siliao').val(rewards[i]['nums']);
                        $('#s_probability').val(rewards[i]['probability']);
                        break;
                    case 3:
                        $('input[type=checkbox]').each(function () {
                            let val = $(this).val();
                            var name = $(this).attr("name");
                            if(val == rewards[i].id && name == 'yhq[]') {
                                $('input:checkbox[value='+val+']').prop('checked',true);
                                $('#pyhq_'+ rewards[i].id).val(rewards[i]['probability']);
                            }
                        });
                        break;
                    case 4:
                        $('#no_reward').val(rewards[i]['probability']);
                        break;
                }
            }

            $('#modal-add-admin').modal({
                backdrop: 'static',
            });
        });

        $('.submit_form').click(function() {
            var cycle = $('#cycle').val().replace(/(^\s*)|(\s*$)/g, '');
            if (cycle == '' || cycle == undefined || cycle == null) {
                $('#cycle').focus();
                return false;
            }
            var feed_times = $('#feed_times').val().replace(/(^\s*)|(\s*$)/g, '');
            if (feed_times == '' || feed_times == undefined || feed_times == null) {
                $('#feed_times').focus();
                return false;
            }

            // 增加验证, 权重和数值缺一不可
            // 饲料验证
            var siliao = $('#siliao').val();
            var sils_probabilityiao = $('#s_probability').val();
            var siliao = siliao.replace(/(^\s*)|(\s*$)/g, '');//去除空格;
            var sils_probabilityiao = sils_probabilityiao.replace(/(^\s*)|(\s*$)/g, '');//去除空格;
            if(siliao) {
                if (sils_probabilityiao == '' || sils_probabilityiao == undefined || sils_probabilityiao == null) {
                    $('#s_probability').focus();
                    return false;
                }
            }
            // 优惠券验证
            var yhq = document.getElementsByName("yhq[]");
            var pyhq = document.getElementsByName("pyhq[]");
            // console.log(yhq);
            // console.log(pyhq);
            // return;
            //遍历这些名称为sex的标签
            for(var i=0;i<yhq.length;++i){
                //如果某个sex被选中，则记录
                if(yhq[i].checked) {
                    var val = pyhq[i].value.replace(/(^\s*)|(\s*$)/g, '');//去除空格;;
                    if (val == '' || val == undefined || val == null) {
                        $('#'+ pyhq[i].id).focus();
                        return false;
                    }
                }
            }

            // 皮肤验证
            var derssup = document.getElementsByName("derssup[]");
            var pdressup = document.getElementsByName("pdressup[]");
            // console.log(derssup);
            // console.log(pdressup);
            //遍历这些名称为sex的标签
            for(var i=0;i<derssup.length;++i){
                //如果某个sex被选中，则记录
                if(derssup[i].checked) {
                    var val = pdressup[i].value.replace(/(^\s*)|(\s*$)/g, '');//去除空格;;
                    if (val == '' || val == undefined || val == null) {
                        $('#'+ pdressup[i].id).focus();
                        return false;
                    }
                }
            }
            $('#item_form').submit();
        });

        $('.del_notice').click(function() {
            if(confirm('确认删除吗？\n\n！！！！！ 该操作不可恢复 ！！！！！\n\n')) {
                var iid = $(this).attr('iid');
                location.href = 'red_packet_list.php?action=del&id=' + iid;
            }
        });

        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);
    });
</script>

</body>
</html>

